/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: HomePresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.main.presenter;

import android.os.Bundle;
import android.text.TextUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.bhex.app.base.AppUI;
import io.bhex.app.main.ui.HomeFragment;
import io.bhex.app.market.api.MarketApi;
import io.bhex.app.trade.sort.CoinPairComparator;
import io.bhex.app.utils.CommonUtil;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BaseFragmentPresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.sdk.config.ConfigApi;
import io.bhex.sdk.config.bean.IndexModuleItem;
import io.bhex.sdk.config.bean.IndexMudulesResponse;
import io.bhex.sdk.data_manager.MMKVManager;
import io.bhex.sdk.enums.COIN_TYPE;
import io.bhex.sdk.point.PointCardApi;
import io.bhex.sdk.point.bean.AdvertisementListResponse;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.CoinPairListBean;
import io.bhex.sdk.quote.bean.NewCoinPairListBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.quote.bean.TickerListBean;
import io.bhex.sdk.socket.NetWorkObserver;
import io.bhex.sdk.utils.CacheUtils;
import io.bhex.sdk.utils.UtilsApi;
import io.bhex.sdk.utils.bean.AnnouncementsResponse;
import io.bhex.sdk.utils.bean.BannerResponse;

/**
 * ================================================
 * 描   述：首页
 * ================================================
 */

public class HomePresenter extends BaseFragmentPresenter<HomePresenter.HomeUI>{

    private List<CoinPairBean> coinPairList = new ArrayList<>();
    private boolean isSendDefaultCoinPair = false;
    //上次更新列表时间
    private long lastTime = 0l;
    private long lastTimeOption=0l;
    private Timer timer;
    private TimerTask timerTask;
    private List<CoinPairBean> recommendSymbolsList;

    public interface HomeUI extends AppUI {

        void showBanner(List<BannerResponse.BannerBean> bannerList);

        void showAnnounces(List<AnnouncementsResponse.AnnounceBean> data);

        int getTab();

        void showSymbolVp(List<CoinPairBean> listData);

        void changeSymbolVpData(List<TickerBean> datas);

        void showNineEntry(ArrayList<IndexModuleItem> nineEntryData);

        void showSymbolVpVisible(boolean isVisible);

        void showTitleLogo(String defaultIcon);
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, HomeUI ui) {
        super.onUIReady(activity, ui);

        loadCache();
//        getRecommendSymbols();

    }

    private void loadCache() {

        loadBannerCache();
        loadConfigCache();
    }

    private void loadConfigCache() {
        IndexMudulesResponse indexMoudles = CacheUtils.getCacheObject("indexMoudles"+ "_" +CommonUtil.isBlackMode(), IndexMudulesResponse.class);
        if (indexMoudles != null) {
            ArrayList<IndexModuleItem> nineEntryData = indexMoudles.getType1();
            getUI().showNineEntry(nineEntryData);
            ArrayList<IndexModuleItem> titleLogo = indexMoudles.getType4();
            if (titleLogo != null && titleLogo.size()>0) {

                IndexModuleItem indexModuleItem = titleLogo.get(0);
                if (indexModuleItem == null) {
                    return;
                }
                String defaultIcon = indexModuleItem.getDefaultIcon();
                getUI().showTitleLogo(defaultIcon);
            }

        }
    }

    /**
     * 缓存-加载banner
     */
    private void loadBannerCache() {

        BannerResponse bannerResponse = CacheUtils.getCacheObject("banner",BannerResponse.class);

        if (bannerResponse != null) {
            List<BannerResponse.BannerBean> bannerList = bannerResponse.getArray();
            if (bannerList != null) {
                getUI().showBanner(bannerList);
            }
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 刷新banner和公告
     */
    public void Refresh(){
        requestHomeData();
    }

    private void requestHomeData() {
        requestBanners();
        requestAnnounce();
        getRecommendSymbols();
        getIndexModules();
    }

    /**
     * 1-中部宫格导航 2-底部tab导航 3-开屏图片 4-home logo
     */
    private void getIndexModules() {
        ConfigApi.getIndexModules("1,2,4", CommonUtil.isBlackMode()?0:1,new SimpleResponseListener<IndexMudulesResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(IndexMudulesResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    CacheUtils.saveCache("indexMoudles" + "_" +CommonUtil.isBlackMode(),response);
                    ArrayList<IndexModuleItem> nineEntryData = response.getType1();
                    getUI().showNineEntry(nineEntryData);

                    ArrayList<IndexModuleItem> titleLogo = response.getType4();
                    if (titleLogo != null && titleLogo.size()>0) {

                        IndexModuleItem indexModuleItem = titleLogo.get(0);
                        if (indexModuleItem == null) {
                            return;
                        }
                        String defaultIcon = indexModuleItem.getDefaultIcon();
                        if (!TextUtils.isEmpty(defaultIcon)) {
                            MMKVManager.getInstance().saveHomeLogoUrl(defaultIcon);
                        }
                        getUI().showTitleLogo(defaultIcon);
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });

    }

    /**
     * 请求公告
     */
    public void requestAnnounce() {
        UtilsApi.RequestAnnouncements(new SimpleResponseListener<AnnouncementsResponse>(){
            @Override
            public void onSuccess(AnnouncementsResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    List<AnnouncementsResponse.AnnounceBean> data = response.getArray();
                    if (data!= null) {
                        getUI().showAnnounces(data);
                    }
                }
            }
        });
    }

    /**
     * 点卡入口广告
     */
    public void requestPointCard(){
        PointCardApi.requestAdvertisementList(new SimpleResponseListener<AdvertisementListResponse>(){
            @Override
            public void onSuccess(AdvertisementListResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)){

                    if (response.getData() != null && response.getData().getAdvertisementList()!= null) {
                        if(response.getData().getAdvertisementList().size() >0 && response.getData().getAdvertisementList().get(0)!= null){

//                            getUI().showPointImage(response.getData().getAdvertisementList().get(0).getPicUrl());
                        }
                    }
                }
            }
        });
    }

    /**
     * 获取banner列表
     */
    public void requestBanners() {
        UtilsApi.RequestBanners(new SimpleResponseListener<BannerResponse>(){
            @Override
            public void onSuccess(BannerResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)){
                    List<BannerResponse.BannerBean> bannerList = response.getArray();
                    if (bannerList != null&&bannerList.size()>0) {
//                        //新数据
//                        String bannerJsonStr = JsonConvertor.getInstance().toJson(response);
//                        //缓存数据
//                        String bannerJsonStrCache = SPEx.get("banner", "");
//                        if (!TextUtils.isEmpty(bannerJsonStr)&&!TextUtils.isEmpty(bannerJsonStrCache)) {
//                            if (bannerJsonStrCache.equals(bannerJsonStr)) {
//                                //数据相同，不再重复刷新界面
//                                return;
//                            }
//                        }

                        CacheUtils.saveCache("banner",response);
                        getUI().showBanner(bannerList);//更新
//                        SPEx.set("banner",bannerJsonStr);//保存
                    }else{
                        SPEx.set("banner","");//保存
                    }
                }
            }
        });
    }


    @Override
    public void onPause() {
        super.onPause();
//        NetWorkApiManager.getQuoteInstance().UnSubRequestNetWork("realtimes");
    }

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        DebugLog.e("RANK-MARKET-HOME-onVisibleChanged",this.hashCode() + " " + visible);
        if (visible) {
            requestHomeData();

        }else{
            QuoteApi.UnSubTickers();
        }

    }

    HashMap<String,CoinPairBean> symbolMap = new HashMap<String,CoinPairBean>();

    /**
     * 处理币对列表数据
     *
     * @param dataList
     */
    private void saveCoinPairListToMap(int type,List<CoinPairBean> dataList) {
        if (dataList != null && dataList.size() > 0) {
            if (type == HomeFragment.TAB_BB) {
                coinPairList = dataList;
                symbolMap.clear();
                for (CoinPairBean coinPairBean : dataList) {
//                    coinPairBean.setCoinType(COIN_TYPE.COIN_TYPE_BB.getCoinType());
                    symbolMap.put(coinPairBean.getSymbolId(),coinPairBean);
                }
            }
        }
    }


    /**
     * 拼接行情参数
     *
     * @return
     */
    private String getSymbolsListStr(List<CoinPairBean> list) {
        StringBuffer stringBuffer = new StringBuffer();
        if (list != null && list.size() > 0) {
            for (CoinPairBean coinPairBean : list) {
                if (coinPairBean != null) {
                    String symbol = coinPairBean.getExchangeId() + "." + coinPairBean.getSymbolId();
                    if (stringBuffer.toString().length() > 0) {
                        stringBuffer.append("," + symbol);
                    } else {
                        stringBuffer.append(symbol);
                    }
                }
            }

        }
        return stringBuffer.toString();
    }

    public synchronized void getRealTimeData(String symbolsListStr){
        if(TextUtils.isEmpty(symbolsListStr))
            return;
        if(recommendSymbolsList.size() > 0){
            QuoteApi.UnSubTickers();
        }
        QuoteApi.SubTickers(symbolsListStr, new NetWorkObserver<TickerListBean>() {
            @Override
            public void onShowUI(TickerListBean response) {
                if (getUI() == null || !getUI() .isAlive() || response == null)
                    return;
                try{
                    List<TickerBean> datas = response.getData();
                    if (datas != null) {
                        //赋值行情数据
                        for (TickerBean data : datas) {

                            CoinPairBean coinPairBean = symbolMap.get(data.getS());
                            if (coinPairBean != null) {
                                coinPairBean.setTicker(data);
                            }
                        }
                        long durTime = System.currentTimeMillis()-lastTime;
                        if (durTime>=300) {
//                            recommendSymbolsList.clear();
//                            for (String key : symbolMap.keySet()) {
//                                CoinPairBean coinPairBean = symbolMap.get(key);
//                                recommendSymbolsList.add(coinPairBean);
//                            }
                            getUI().showSymbolVp(recommendSymbolsList);
                        }

                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String error) {
            }
        });
    }

    /**
     * 比较器排序
     *
     * @param mData
     * @param sortType
     */
    private void sortByComparator(List<CoinPairBean> mData, int sortType) {
        try{
            Collections.sort(mData, new CoinPairComparator(sortType));
        }catch(Exception e){
        }
        if (mData!=null&&mData.size()>5) {
            mData = mData.subList(0, 5);
        }
//        getUI().showUpOrDownSymbol(mData);
    }


    /**
     * APP首次打开提示交易界面使用的默认币对
     * @param coinPairListBean
     */
    private void notifyTradeCoinPair(NewCoinPairListBean coinPairListBean) {
        //第一次发送默认币对提示
        if (isSendDefaultCoinPair) {
            return;
        }
        if (coinPairListBean.symbol!=null && coinPairListBean.symbol.size() > 0) {
            CoinPairBean coinPairBean = coinPairListBean.symbol.get(0);
            coinPairBean.setNeedSwitchTradeTab(false);
            EventBus.getDefault().postSticky(coinPairBean);
            isSendDefaultCoinPair = true;
        }
        if (coinPairListBean.optionSymbol!=null && coinPairListBean.optionSymbol.size() > 0) {
            CoinPairBean coinPairBean = coinPairListBean.optionSymbol.get(0);
            coinPairBean.setNeedSwitchTradeTab(false);
            EventBus.getDefault().postSticky(coinPairBean);
            isSendDefaultCoinPair = true;
        }
        if (coinPairListBean.futuresSymbol!=null && coinPairListBean.futuresSymbol.size() > 0) {
            CoinPairBean coinPairBean = coinPairListBean.futuresSymbol.get(0);
            coinPairBean.setNeedSwitchTradeTab(false);
            EventBus.getDefault().postSticky(coinPairBean);
            isSendDefaultCoinPair = true;
        }

    }


    /**
     * 获取推荐币对
     */
    private void getRecommendSymbols() {
        MarketApi.getRecommendSymbols(new SimpleResponseListener<CoinPairListBean>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(CoinPairListBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    List<CoinPairBean> symbolsList = response.getArray();
                    //TODO 测试数据
//                    CoinPairBean defaultFuturesTradeCoinPair = SymbolDataManager.GetInstance().getDefaultFuturesTradeCoinPair();
//                    if (defaultFuturesTradeCoinPair != null) {
//                        symbolsList.add(defaultFuturesTradeCoinPair);
//                    }
//                    CoinPairBean defaultOptionTradeCoinPair = SymbolDataManager.GetInstance().getDefaultOptionTradeCoinPair();
//                    if (defaultOptionTradeCoinPair != null) {
//                        symbolsList.add(defaultOptionTradeCoinPair);
//                    }
                    /*new AsyncTask<String,Void,String>(){
                        @Override
                        protected String doInBackground(String... strings) {
                            return null;
                        }
                    };*/
                    handCoinPairListData(symbolsList);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 推荐币对行情
     * @param symbolsList
     */
    private void requestRecommendSysmbolsTicker(List<CoinPairBean> symbolsList) {
        if (symbolsList != null&&symbolsList.size()>0) {
            QuoteApi.RequestTickers(symbolsList,new SimpleResponseListener<TickerListBean>(){
                @Override
                public void onBefore() {
                    super.onBefore();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                }

                @Override
                public void onSuccess(TickerListBean response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response)) {
                        List<TickerBean> datas = response.getData();
                        if (datas != null) {
                            getUI().changeSymbolVpData(datas);
                        }
                    }
                }

                @Override
                public void onError(Throwable error) {
                    super.onError(error);
                }
            });
        }
    }

    private void subRecommendSymbols(List<CoinPairBean> symbolsList) {
        if(symbolsList != null && symbolsList.size() > 0){
            getRealTimeData(getSymbolsListStr(symbolsList));
        }
    }

    /**
     * 处理币对列表数据
     *
     * @param listBean
     */
    private void handCoinPairListData(List<CoinPairBean> listBean) {
        if (listBean !=null && listBean.size()>0) {
            if(!getSymbolsListStr(listBean).equals(getSymbolsListStr(recommendSymbolsList))){
                //推荐币种不一样
                for (CoinPairBean coinPairBean : listBean) {
                    if (coinPairBean != null) {
                        int category = coinPairBean.getCategory();  // 1-币币 2-创新币 3-期权 4-合约
                        if (category == 1) {
                            coinPairBean.setCoinType(COIN_TYPE.COIN_TYPE_BB.getCoinType());
                        } else if (category == 3) {
                            coinPairBean.setCoinType(COIN_TYPE.COIN_TYPE_OPTION.getCoinType());
                        } else if (category == 4) {
                            coinPairBean.setCoinType(COIN_TYPE.COIN_TYPE_PERPETUAL_CONTRACT.getCoinType());
                        }
                    }
                }
                recommendSymbolsList = listBean;
                saveCoinPairListToMap(HomeFragment.TAB_BB,recommendSymbolsList);
                getUI().showSymbolVp(listBean);
            }
        }else{
            getUI().showSymbolVpVisible(false);
        }

        if (recommendSymbolsList != null&&recommendSymbolsList.size()>0) {
            subRecommendSymbols(recommendSymbolsList);
        }
    }

}